﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility.Helper
{
    /// <summary>
    /// 端口助手类
    /// </summary>
    public class PortHelper
    {
        /// <summary>
        /// 端口混淆
        /// </summary>
        /// <param name="port">端口</param>
        /// <param name="confuseString">混淆字符串</param>
        /// <returns></returns>
        public static int? Confuse(int? port,string confuseString)
        {
            return Confuse(port, confuseString.Length);
        }

        /// <summary>
        /// 混淆长度
        /// </summary>
        /// <param name="port"></param>
        /// <param name="confuseOffset">混淆偏移</param>
        /// <returns></returns>
        public static int? Confuse(int? port, int confuseOffset)
        {
            //端口
            int? confusePort = port;
            if (confusePort != null)
            {
                if (confusePort + confuseOffset > 65535)
                {
                    var str = Math.Abs(0 - confusePort.GetValueOrDefault(0) - confuseOffset).ToString();
                    var newStr = string.Join("",str.Reverse());
                    confusePort = ValueTypeConvertHelper.ToInt(newStr) * -1;
                }
                else
                {
                    confusePort = confusePort + confuseOffset;
                }
            }
            return confusePort;
        }

        /// <summary>
        /// 取消端口混淆
        /// </summary>
        /// <param name="port">端口</param>
        /// <param name="confuseString">混淆字符串</param>
        /// <returns></returns>
        public static int? CancelConfuse(int? port, string confuseString)
        {
            return CancelConfuse(port, confuseString.Length);
        }

        /// <summary>
        /// 取消端口混淆
        /// </summary>
        /// <param name="port"></param>
        /// <param name="confuseOffset">混淆偏移</param>
        /// <returns></returns>
        public static int? CancelConfuse(int? port, int confuseOffset)
        {
            //端口
            int? confusePort = port;
            if (confusePort != null)
            {
                if(confusePort < 0)
                {
                    var str = Math.Abs(confuseOffset).ToString();
                    //字符串倒序
                    var newStr = string.Join("",str.Reverse());
                    confusePort = Math.Abs(ValueTypeConvertHelper.ToInt(newStr) * -1 + confuseOffset);
                }
                else
                {
                    confusePort = confusePort - confuseOffset;
                }
            }
            return confusePort;
        }
    }
}
